<?php

namespace App\Http\Controllers\Admin\newWork;

use App\Http\Config\ErrorCode;
use App\Models\Admin\Configs;
use App\Models\Admin\Picture;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SettingController extends CommonController
{
    private $tableName = "new_work_setting";
    private $field = [
        "banner" => NULL, "intro" => NULL, "frame_color" => NULL, "title_color1" => NULL, "title_color2" => NULL
    ]; // 填入数据库需要存储的表字段;
    private $fieldMsg = [
        "banner" => "banner图", "intro" => "文字介绍", "frame_color" => "边框颜色", "title_color1" => "主标题颜色", "title_color2" => "副标题颜色"
    ];
    private $msgField = [
        "sms_reply_template" => NULL, "wx_reply_template" => NULL, "wx_pay_template" => NULL, "sms_remind_order" => null, "remind_mobile" => null
    ]; // 填入数据库需要存储的表字段;
    private $msgFieldMsg = [
        "sms_reply_template" => "回复短信模板", "wx_reply_template" => "回复微信模板消息", "wx_pay_template" => "支付成功模板消息"
    ];
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function getInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = DB::table($this->tableName)->where("mall_id", $request->mallData['id'])->first();
        $res = json_decode(json_encode($res),true);
        if(!$res) {
            foreach ($this->field as $v => $k) {
                $res[$v] = '';
            }
            foreach ($this->msgField as $v => $k) {
                $res[$v] = '';
            }
        }
        $this->returnData['data'] = $this->transferFields($res);
        $this->returnData['data']["banner"] = $this->processingPictures($this->returnData["data"]["banner"]);
        return $this->return_result($this->returnData);
    }

    public function update(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !isset($params[$ks])){
                return $this->return_result(ErrorCode::$admin_enum["customized"], "{$this->fieldMsg[$k]}不能为空");
            }
            $data[$k] = isset($params[$ks]) ? trim($params[$ks]) : $v;
        }
        $r = DB::table($this->tableName)->select("id")->where("mall_id", $request->mallData['id'])->first();
        if(!empty($r->id)) {
            $res = DB::table($this->tableName)->where("id", $r->id)->update($data);
        }else{
            $data['mall_id'] = $request->mallData['id'];
            $res = DB::table($this->tableName)->insert($data);
        }
        if(!$res && $res != '0'){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }

    public function updateMsg(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        foreach ($this->msgField as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !isset($params[$ks])){
                return $this->return_result(ErrorCode::$admin_enum["customized"], "{$this->msgFieldMsg[$k]}不能为空");
            }
            $data[$k] = isset($params[$ks]) ? trim($params[$ks]) : $v;
        }
        $r = DB::table($this->tableName)->select("id")->where("mall_id", $request->mallData['id'])->first();
        if(!empty($r->id)) {
            $res = DB::table($this->tableName)->where("id", $r->id)->update($data);
        }else{
            $data['mall_id'] = $request->mallData['id'];
            $res = DB::table($this->tableName)->insert($data);
        }
        if(!$res && $res != '0'){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }

    /* 附件上传 */
    public function uploadAnnex(Request $request)
    {
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $env = $con->env;
        if ($env == 'CLOUD'){  //配置云开发版
            $base64_img = trim($request->post('file',''));
            if (!$base64_img){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '缺少文件';
                return $this->return_result($this->returnData);
            }
            $files = json_decode($base64_img,true);
            $temp_file = tempnam(sys_get_temp_dir(),"php");  //临时文件
            $content = $files['content'];
            file_put_contents($temp_file,base64_decode($content));        //文件流写入文件
            //创建文件夹
            $time = date('Ymd',time());
            $cloud_file = '/uploads/admin/annex/'.$time;
            $img_name = $cloud_file.'/'.time().$files['name'];
            $pictureModel = new Picture();
            $url = $pictureModel->uploadImg($img_name,$temp_file);
            if (!$url){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '上传文件失败';
                return $this->return_result($this->returnData);
            }
            $result['code'] = 0;
            $result['msg'] = '请求成功';
            $result['data']['url'] = $url['ObjectURL'];
            $result['data']['id'] = $url['ObjectURL'];
        } else{
            $file = $request->file('file');
            if (!$file){
                $this->returnData = ErrorCode::$admin_enum['params_error'];
                $this->returnData['msg'] = '缺少文件';
                return $this->return_result($this->returnData);
            }
            $dir_name = date('Ymd',time());
            $inputFileName = $request->file('file');
            //文件扩展名
            $ext = $inputFileName->getClientOriginalExtension();
            //获取文件的绝对路径
            $path = $inputFileName->getRealPath();
            //定义文件名
            $filename = time().'.'.$ext;
            $new_path = public_path().'/uploads/admin/annex/'.$dir_name;
            if (!is_dir($new_path)){
                mkdir($new_path,0777,true);
            }
            //移动保存文件
            if (move_uploaded_file($path,$new_path.'/'.$filename) && file_exists($new_path.'/'.$filename)){
                $path = 'uploads/admin/annex/'.$dir_name.'/'.$filename;
                $result['code'] = 0;
                $result['msg'] = '上传成功';
                $result['data'] = ['url' => $this->processingPictures($path),'id'=>$this->processingPictures($path)];
            }else{
                $result['code'] = 1;
                $result['msg'] = '上传失败';
            }
        }
        return $this->return_result($result);
    }
}